from src.plug_ins import plug_manage
from lib.config.settings import settings
import requests
from concurrent.futures import ThreadPoolExecutor
import time, json


class Base:
    def post_data(self, info):
        '''采集完以后将数据提交给服务端保存数据'''
        # info = json.dumps(info)
        # print(info)
        # # headers = {'Content-Type': 'application/json'}
        requests.post(url="http://127.0.0.1:8000/post_data/", data=json.dumps(info))
        # requests.post(url="http://127.0.0.1:8000/post_data/", data=json.dumps(info))
        print('数据采集完毕...')


class Agent(Base):
    def collect(self):
        info = plug_manage().parse()  # 取到数据

        for k, v in info.items():
            print(k, v)
        self.post_data(json.dumps(info))


class Ssh(Base):
    def get_hosts(self):
        res = requests.get(settings.API_URL)
        host_list = json.loads(res)
        return host_list

    def collect(self):
        print('开始采集')
        print('...')
        time.sleep(3)
        # host_list = self.get_hosts()  # 所有主机列表
        host_list = ['10.0.0.51']
        # 并发去采集资产信息
        pool = ThreadPoolExecutor(3)
        for host_name in host_list:
            pool.submit(self.run, host_name)

    def run(self, hostname):
        info = plug_manage(hostname).parse()
        self.post_data(info)
